package org.lim.lcpicturebackend.manager.websocket.service.strategy;

import org.lim.lcpicturebackend.manager.websocket.service.PictureEditBroadcastService;
import org.lim.lcpicturebackend.manager.websocket.service.PictureEditStateService;
import org.lim.lcpicturebackend.manager.websocket.model.PictureEditRequestMessage;
import org.lim.lcpicturebackend.manager.websocket.model.PictureEditResponseMessage;
import org.lim.lcpicturebackend.manager.websocket.model.enums.PictureEditMessageTypeEnum;
import org.lim.lcpicturebackend.model.entity.User;
import org.lim.lcpicturebackend.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

@Component("enterEditStrategy")
public class EnterEditStrategy implements PictureEditMessageStrategy {
    
    @Resource
    private UserService userService;
    
    // 注入广播服务
    @Resource
    private PictureEditBroadcastService broadcastService;
    
    // 注入编辑状态管理服务
    @Resource
    private PictureEditStateService stateService;
    
    @Override
    public void handleMessage(PictureEditRequestMessage requestMessage, WebSocketSession session, User user, Long pictureId) throws Exception {
        // 没有用户正在编辑图片，才能进入编辑
        if (!stateService.isEditingByOthers(pictureId)) {
            // 设置当前用户为编辑用户
            stateService.setEditingUser(pictureId, user.getId());
            
            PictureEditResponseMessage responseMessage = new PictureEditResponseMessage();
            responseMessage.setType(PictureEditMessageTypeEnum.ENTER_EDIT.getValue());
            String message = String.format("%s开始编辑图片", user.getUserName());
            responseMessage.setMessage(message);
            responseMessage.setUser(userService.getUserVO(user));
            
            broadcastService.broadcastToPicture(pictureId, responseMessage);
        }
    }
}
